package org.zsqx.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.zsqx.bean.Admin;
import org.zsqx.bean.CountTimes;
import org.zsqx.bean.Linkman;
import org.zsqx.bean.LinkmanBean;
import org.zsqx.bean.LinkmanType;
import org.zsqx.bean.PointsExcel;
import org.zsqx.bean.Town;
import org.zsqx.bean.YjUser;
import org.zsqx.dao.ZdzReportDAOImpl;
import org.zsqx.tools.ExcelTools;
import org.zsqx.tools.LotusTools;
import org.zsqx.tools.PropertiesTools;
import org.zsqx.tools.SMSTools;
import org.zsqx.tools.UploadTools;

import cDao.annotation.OrderByEnum;
import cDao.annotation.SearchTypeEnum;

@Action(value="/adminAction",results={
		@Result(name="isUser",location="/main.zs",type="redirect"),
		@Result(name="msgPage",location="/login/msg/msgSent.jsp"),
		@Result(name="msgPageAction",location="/adminAction!msgPage.action",type="redirect"),
		@Result(name="countPage",location="/login/system/credit.jsp"),
		@Result(name="countPage2",location="/login/system/credit2.jsp"),
		@Result(name="linkmanCount",location="/adminAction!linkmanCount.action",type="redirect"),
		@Result(name="pointDetailPage",location="/login/system/pointDetail.jsp"),
		@Result(name="searchMan",location="/login/msg/msgSent.jsp"),
		@Result(name="outputExcel",type="stream",params={"contentType","application/vnd.ms-excel","bufferSize","2046","inputName","excelStream","contentDisposition","attachment;filename=${fileNames}"}),
		@Result(name="login",location="/login.jsp",type="redirect")
})
public class AdminAction extends BaseAction {
	private Admin admin;
	private List<LinkmanBean> manList;
	private List<LinkmanType> manTypeList;
	private String man;
	private String message;
	private Linkman linkman;
	private LinkmanBean linkmanBean;
	private List<Linkman> linkmanList;
	private YjUser yjUser;
	private Integer bbsLoginCount;
	private CountTimes countTimes;
	private List<Town> townList;
	private String linkmanPointRemark;
	private InputStream excelStream;
	private String fileNames;
	private File upload;
	private String uploadFileName;
	private String uploadContentType;
	
	public String isUser(){
		String url=request.getRequestURL().toString();
		String domain=url.substring(0,url.indexOf('/',7));
		PropertiesTools.domain=domain;
		admin=(Admin) rd.findOne(admin);
		if (null!=admin) {
			session.put("admin", admin);
			return "isUser";
		}else{
			message="用户名或密码错误!";
			return "login";
		}
	}
	public String msgPage(){
		manList = rd.find(new LinkmanBean());
		manTypeList = rd.find(new LinkmanType());
		townList=rd.find(new Town());
		return "msgPage";
	}
	public String msgSend(){
		man = man.replace(" ", "");
		if(SMSTools.mySendSMS(man,message)){
			message = "短信发送成功！";
		}else{
			message = "短信发送失败！";
		}
		return "msgPageAction";
	}
	
	public String logout(){
		request.getSession().invalidate();
		return "login";
	}
	//信息员积分
	public String linkmanCount() throws SecurityException, SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException{
		rd.setOrderBy(OrderByEnum.DESC).setOrderByField("last_point");
		if(linkman==null){
			linkman = new Linkman();
		}else{
			rd.setSearchType(SearchTypeEnum.HEAD);
		}
		linkmanList = rd.find(linkman);
		PropertiesTools pt = new PropertiesTools();
		linkmanPointRemark = pt.getPropertiesValue("linkmanPointRemark");
		return "countPage";
	}
	//其他网连信息员积分
	public String linkmanCount2() throws SecurityException, SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException{
		rd.setOrderBy(OrderByEnum.DESC).setOrderByField("last_point");
		if(linkman==null){
			linkman = new Linkman();
		}else{
			rd.setSearchType(SearchTypeEnum.HEAD);
		}
		linkmanList = rd.find(linkman);
		PropertiesTools pt = new PropertiesTools();
		linkmanPointRemark = pt.getPropertiesValue("linkmanPointRemark");
		return "countPage2";
	}
	//
	public String searchMan(){
		if(linkmanBean==null){
			linkmanBean = new LinkmanBean();
		}else{
			rd.setSearchType(SearchTypeEnum.HEAD);
		}
		manTypeList = rd.find(new LinkmanType());
		linkmanList = rd.find(linkmanBean);
		townList=rd.find(new Town());
		System.out.println(linkmanList);
		return "searchMan";
	}
	public String setLinkmanPointRemark() throws SecurityException, SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException{
		PropertiesTools pt = new PropertiesTools();
		pt.setPropertiesValue("linkmanPointRemark",linkmanPointRemark);
		return linkmanCount();
	}
	public String countFlush() throws SecurityException, SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException{
		ZdzReportDAOImpl zd = new ZdzReportDAOImpl();
		PropertiesTools pt = new PropertiesTools();
		CountTimes ct = (CountTimes) pt.getPropertyesBean(new CountTimes());
		boolean su = zd.linkmanCountSet(ct,rd.find(new Linkman()));
		return linkmanCount();
	}
	public String changePoint() throws NullPointerException,SecurityException, SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException{
		Double changePoint = linkman.getChangePoint();
		linkman.setChangePoint(null);
		linkman = (Linkman) rd.findById(linkman);
		linkman.setChangePoint(changePoint);
		linkman.setLastPoint(linkman.getCountPoint()+changePoint);
		rd.update(linkman);
		return "linkmanCount";
	}
	public String pointDetail(){
		yjUser = (YjUser) rd.findOne(yjUser);
		linkmanBean = (LinkmanBean) rd.findById(linkmanBean);
		ZdzReportDAOImpl zd = new ZdzReportDAOImpl();
		bbsLoginCount = zd.getBbsLoginCount(yjUser.getUsername());
		PropertiesTools pt = new PropertiesTools();
		countTimes = (CountTimes) pt.getPropertyesBean(new CountTimes());
		return "pointDetailPage";
	}
	
	public String outputAllUsersExcel() throws Exception{
//		String absolute_path=request.getRealPath("/");
//		Map<String, String> map=new HashMap<String, String>();
//		map.put("lmName", "姓名");
//		map.put("rightScore", "权重");
//		map.put("upwcount", "气象灾害上报高清图片次数");
//		map.put("upwcountPoint", "气象灾害上报高清图片分数");
//		map.put("uplcount", "气象灾害上报一般图片次数");
//		map.put("uplcountPoint", "气象灾害上报一般图片分数");
//		map.put("upcount", "气象灾害上报无图片次数");
//		map.put("upcountPoint", "气象灾害上报无图片分数");
//		map.put("b3wcount", "冰雹龙卷风上报高清图片次数");
//		map.put("b3wcountPoint", "冰雹龙卷风上报高清图片 分数");
//		map.put("b3lcount", "冰雹龙卷风上报一般图片次数");
//		map.put("b3lcountPoint", "冰雹龙卷风上报一般图片分数");
//		map.put("b3count", "冰雹龙卷风上报无图片分数");
//		map.put("b3countPoint", "冰雹龙卷风上报无图片分数");
//		map.put("b2count", "预警信号接收.传播记录上报次数");
//		map.put("b2countPoint", "预警信号接收.传播记录上报分数");
//		map.put("b4count", "自动气象站巡查检查维护记录上报次数");
//		map.put("b4countPoint", "自动气象站巡查检查维护记录上报分数");
//		map.put("b5count", "电子显示屏检查维护记录上报次数 ");
//		map.put("b5countPoint", "电子显示屏检查维护记录上报分数");
//		map.put("b6count", "会议及活动记录上报次数");
//		map.put("b6countPoint", "会议及活动记录上报分数");
//		map.put("b7count", "气象需求反馈信息上报次数 ");
//		map.put("b7countPoint", "气象需求反馈信息上报分数");
//		map.put("logincount", "信息员登录管理平台次数记录上报次数");
//		map.put("logincountPoint", "信息员登录管理平台次数记录上报分数");
//		map.put("bbslogincount", "论坛登录次数记录上报次数");
//		map.put("bbslogincountPoint", "论坛登录次数记录上报分数");
//		map.put("extraPoint", "额外加分 ");
//		map.put("sumPoint", "总分");
//		List<PointsExcel> excelList=ExcelTools.getAllUsersPoints();
//		if (excelList.size()>0) {
//			String down_path=ExcelTools.writeToExcel("会员积分", absolute_path,excelList, map);
//			BufferedInputStream bis = null;
//			BufferedOutputStream bos = null;
//			OutputStream fos = null;
//			InputStream fis = null;
//			File uploadFile = new File(down_path);
//			try {
//				fis = new FileInputStream(uploadFile);
//				bis = new BufferedInputStream(fis);
//				fos = response.getOutputStream();
//				bos = new BufferedOutputStream(fos);
//				String fileName=down_path.substring(down_path.lastIndexOf("\\")+1,down_path.length());
//				//System.out.println(fileName);
//				response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, "utf-8"));
//				int bytesRead = 0;
//				byte[] buffer = new byte[8192];
//				while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
//					bos.write(buffer, 0, bytesRead);
//				}
//				bos.flush();
//				fis.close();
//				bis.close();
//				fos.close();
//				bos.close();
//			} catch (FileNotFoundException e) {
//				e.printStackTrace();
//			} catch (UnsupportedEncodingException e) {
//				e.printStackTrace();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
		return "outputExcel";
	}
	
	//发送Lotus邮件
	public void sendLotus() throws IOException{
		LotusTools lt = new LotusTools();
		String root = servletContext.getRealPath("resources/disasterUpload");
    	UploadTools ut = new UploadTools();
    	String fileName="";
		try {
			fileName = ut.upload(root, upload, root + uploadFileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		boolean send = lt.sendMail("灾情报文发送", root +"\\"+ fileName,"word");
		if(send){
			response.getWriter().println("<script>parent.getContext('success');</script>");
		}else{
			response.getWriter().println("<script>parent.getContext('fail');</script>");
		}
	}
	
	public Admin getAdmin() {
		return admin;
	}

	public void setAdmin(Admin admin) {
		this.admin = admin;
	}

	public List<LinkmanBean> getManList() {
		return manList;
	}

	public void setManList(List<LinkmanBean> manList) {
		this.manList = manList;
	}
	public String getMan() {
		return man;
	}
	public void setMan(String man) {
		this.man = man;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public List<LinkmanType> getManTypeList() {
		return manTypeList;
	}
	public void setManTypeList(List<LinkmanType> manTypeList) {
		this.manTypeList = manTypeList;
	}
	public Linkman getLinkman() {
		return linkman;
	}
	public void setLinkman(Linkman linkman) {
		this.linkman = linkman;
	}
	public List<Linkman> getLinkmanList() {
		return linkmanList;
	}
	public void setLinkmanList(List<Linkman> linkmanList) {
		this.linkmanList = linkmanList;
	}
	public YjUser getYjUser() {
		return yjUser;
	}
	public void setYjUser(YjUser yjUser) {
		this.yjUser = yjUser;
	}
	public Integer getBbsLoginCount() {
		return bbsLoginCount;
	}
	public void setBbsLoginCount(Integer bbsLoginCount) {
		this.bbsLoginCount = bbsLoginCount;
	}
	public CountTimes getCountTimes() {
		return countTimes;
	}
	public void setCountTimes(CountTimes countTimes) {
		this.countTimes = countTimes;
	}
	public LinkmanBean getLinkmanBean() {
		return linkmanBean;
	}
	public void setLinkmanBean(LinkmanBean linkmanBean) {
		this.linkmanBean = linkmanBean;
	}
	public List<Town> getTownList() {
		return townList;
	}
	public void setTownList(List<Town> townList) {
		this.townList = townList;
	}
	
	public String getLinkmanPointRemark() {
		return linkmanPointRemark;
	}
	public void setLinkmanPointRemark(String linkmanPointRemark) {
		this.linkmanPointRemark = linkmanPointRemark;
	}
	public InputStream getExcelStream() {
		String absolute_path=request.getRealPath("/");
		Map<String, String> map=new HashMap<String, String>();
		map.put("lmName", "姓名");
		map.put("rightScore", "权重");
		map.put("upwcount", "气象灾害上报高清图片次数");
		map.put("upwcountPoint", "气象灾害上报高清图片分数");
		map.put("uplcount", "气象灾害上报一般图片次数");
		map.put("uplcountPoint", "气象灾害上报一般图片分数");
		map.put("upcount", "气象灾害上报无图片次数");
		map.put("upcountPoint", "气象灾害上报无图片分数");
		map.put("b3wcount", "冰雹龙卷风上报高清图片次数");
		map.put("b3wcountPoint", "冰雹龙卷风上报高清图片 分数");
		map.put("b3lcount", "冰雹龙卷风上报一般图片次数");
		map.put("b3lcountPoint", "冰雹龙卷风上报一般图片分数");
		map.put("b3count", "冰雹龙卷风上报无图片分数");
		map.put("b3countPoint", "冰雹龙卷风上报无图片分数");
		map.put("b2count", "预警信号接收.传播记录上报次数");
		map.put("b2countPoint", "预警信号接收.传播记录上报分数");
		map.put("b4count", "自动气象站巡查检查维护记录上报次数");
		map.put("b4countPoint", "自动气象站巡查检查维护记录上报分数");
		map.put("b5count", "电子显示屏检查维护记录上报次数 ");
		map.put("b5countPoint", "电子显示屏检查维护记录上报分数");
		map.put("b6count", "会议及活动记录上报次数");
		map.put("b6countPoint", "会议及活动记录上报分数");
		map.put("b7count", "气象需求反馈信息上报次数 ");
		map.put("b7countPoint", "气象需求反馈信息上报分数");
		map.put("logincount", "信息员登录管理平台次数记录上报次数");
		map.put("logincountPoint", "信息员登录管理平台次数记录上报分数");
		map.put("bbslogincount", "论坛登录次数记录上报次数");
		map.put("bbslogincountPoint", "论坛登录次数记录上报分数");
		map.put("extraPoint", "额外加分 ");
		map.put("sumPoint", "总分");
		List<PointsExcel> excelList=ExcelTools.getAllUsersPoints();
		InputStream in=null;
		if (excelList.size()>0) {
			try {
				fileNames=ExcelTools.writeToExcel("会员积分", absolute_path,excelList, map)+".xls";
				String realPath="/login/excel/"+fileNames;
				in=ServletActionContext.getServletContext().getResourceAsStream(realPath);
				if(null==in){
					System.out.println("Can not find a java.io.InputStream with the name [inputStream] in the invocation stack. Check the <param name=\"inputName\"> tag specified for this action.检查action中文件下载路径是否正确.");   
				}
			}catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (RowsExceededException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NullPointerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (WriteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				if(null!=in){
					try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return in;
	}
	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}
	public String getFileNames() {
		return fileNames;
	}
	public void setFileNames(String fileNames) {
		this.fileNames = fileNames;
	}
	
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
}
